package com.wenx;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class RPCProxy {
    public <T> T create(Class<?> clazz) {
        return (T) Proxy.newProxyInstance(clazz.getClassLoader(),
                new Class[]{clazz},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        //若调用的是Object的方法，则进行本地调用
                        if(Object.class.equals(method.getDeclaringClass())) {
                            return method.invoke(this,args);
                        }

                        //远程调用
                        return rpcInvoke(clazz,method,args);
                    }
                });
    }

    private Object rpcInvoke(Class<?> clazz, Method method, Object[] args) throws InterruptedException {

        RPCClientHandler clientHandler = new RPCClientHandler();

        EventLoopGroup loopGroup = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(loopGroup)
                    //只要有信息，就发送
                    .option(ChannelOption.TCP_NODELAY,true)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //InvokeMessage 客户端发送消息设置
                            //ObjectDecoder 解码器
                            pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE,
                                    ClassResolvers.cacheDisabled(null)));
                            //服务器端返回消息设置
                            //编码,添加编码器
                            pipeline.addLast(new ObjectEncoder());
                            //自定义处理器
                            pipeline.addLast(clientHandler);
                        }
                    });
            ChannelFuture future = bootstrap.connect("localhost", 8888).sync();

            //将远程调用信息发送到服务端
            InvokeMessage invokeMessage = new InvokeMessage();
            invokeMessage.setClassName(clazz.getName());
            invokeMessage.setMethodName(method.getName());
            invokeMessage.setParamTypes(method.getParameterTypes());
            invokeMessage.setParamValues(args);
            future.channel().writeAndFlush(invokeMessage).sync();

            future.channel().closeFuture().sync();
        } finally {
            loopGroup.shutdownGracefully();
        }

        return clientHandler.getRPCResult();
    }
}
